package com.enzoism.springboot.juc;

import java.time.Instant;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class MyThreadPoolExecutor2 {
    private static final int CORE_POOL_SIZE = 5;
    private static final int MAX_POOL_SIZE = 20;
    private static final int QUEUE_CAPACITY = 20;
    private static final int KEEP_ALIVE_TIME = 200;

    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(QUEUE_CAPACITY), new MyThreadFactory(), new MyRejectionHandler());
        for (int i = 0; i < 20; i++) {
            threadPoolExecutor.execute(new MyRunable());
        }
        threadPoolExecutor.shutdown();
        threadPoolExecutor.awaitTermination(200, TimeUnit.SECONDS);
        System.out.println("----->线程结束退出");

    }

    private static class MyThreadFactory implements ThreadFactory {
        private AtomicInteger index = new AtomicInteger(1);
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "current thread name - " + index.getAndIncrement());
        }
    }

    private static class MyRunable implements Runnable {
        @Override
        public void run() {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("----->Current Thread Name:" + Thread.currentThread().getName() + " date:" + Instant.now());
        }
    }


    private static class MyRejectionHandler implements RejectedExecutionHandler {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            System.out.println("--------自定义异常策略");
        }
    }
}
